<?php
defined('SYSPATH') or die('No direct script access.');
/**
 * Controller to manage advertiments and partners on website
 *
 * @access public
 * @author an.cao <a@clgt.vn>
 * @since  May 2011
 */
class Controller_Admin_Ads extends Controller_Admin_Layout
{
    /**
     * Show all ads in database
     *
     * @access public
     */
    public function action_manage()
    {
        $data = array();

        // Add jQuery UI
        $this->add_scripts(URL::site($this->assets_js.'/jquery-ui-1.8.13.custom.min.js?' . time()));
        
        // Add CSS
        $this->add_styles(URL::site($this->assets_css.'/ui/jquery-ui-1.8.13.custom.css'));

        // Get all ads
        $ads = Doctrine_Query::create()
                ->from('Ads a')
                ->orderBy('a.id', 'desc')
                ->execute();

        foreach($ads as $obj)
        {
            if($obj->type === 'banner')
            {
                $data[$obj->position][] = $obj;
            }
            else if($obj->type === 'partner')
            {
                $data['partner'][] = $obj;
            }
        }

        $this->template->main = View::factory('admin/ads_manage', $data);
    }

    /**
     * Update information of an ads
     *
     * @access public
     */
    public function action_update()
    {
        if($this->request->is_ajax() === FALSE)
        {
            return;
        }
        
        $post = Validation::factory($_POST)
                ->rule('id', 'not_empty');

        if($post->check() === TRUE)
        {
            $post = Arr::extract($_POST, array('position', 'id'));
            $banner = AdsTable::getInstance()->find($post['id']);

            if($banner == NULL)
            {
                return;
            }
            
            $banner->setArray($post);
            $banner->save();
        }
    }

    /**
     * Delete a banner
     * 
     * @return <type>
     */
    public function action_delete()
    {
        if($this->request->is_ajax() === FALSE)
        {
            return;
        }

        $post = Validation::factory($_POST)
                ->rule('id', 'not_empty');

        if($post->check() === TRUE)
        {
            $post = Arr::extract($_POST, array('id'));
            $banner = AdsTable::getInstance()->find($post['id']);

            if($banner == NULL)
            {
                return;
            }

            $banner->delete();
        }
    }

    /**
     * Create a new ads
     *
     * @access public
     */
    public function action_create()
    {
        $data = array();
        
        if($this->request->method() === 'POST')
        {
            $post = Validation::factory($_FILES)
                    ->rule('image', 'Upload::not_empty')
                    ->rule('image', 'Upload::size', array($_FILES['image'], '1M'))
                    ->rule('image', 'Upload::type', array($_FILES['image'], array('jpg', 'png', 'gif')))
                    ;

            $fields = Validation::factory($_POST)
                    ->rule('url', 'not_empty');

            if($fields->check() !== TRUE)
            {
                $data['message']['type']    = 'error';
                $data['message']['content'] = 'Dữ liệu nhập vào không hợp lệ. Vui lòng thử lại';
            }
            else if($post->check() == TRUE)
            {
                // Save file successully
                $uploaded = Upload::save($_FILES['image'], NULL, Kohana::config('ads.upload_path'));
                if($uploaded !== FALSE)
                {
                    $post = Arr::extract($_POST, array('url', 'type', 'position'));

                    $ads = new Ads();
                    $ads->image    = basename($uploaded);
                    $ads->url      = $post['url'];
                    $ads->type     = $post['type'];
                    $ads->position = $post['position'];

                    try
                    {
                        $ads->save();

                        $data['message']['type']    = 'success';
                        $data['message']['content'] = 'Đã thêm dữ liệu thành công';
                    }
                    catch(Exception $ex)
                    {
                        // TODO: Handle exception
                        $data['message']['type']    = 'error';
                        $data['message']['content'] = 'Đã xảy ra lỗi. Vui lòng thử lại';
                    }
                }
            }
        }
        
        $this->template->main = View::factory('admin/ads_create', $data);
    }

    /**
     * Change the order of displaying banner
     *
     * @access public
     */
    public function action_order()
    {
        $data = array();

        // Add jQuery UI
        $this->add_scripts(URL::site($this->assets_js.'/jquery-ui-1.8.13.custom.min.js?' . time()));

        // Add CSS
        $this->add_styles(URL::site($this->assets_css.'/ui/jquery-ui-1.8.13.custom.css'));

        // Get all ads
        $ads = Doctrine_Query::create()
                ->from('Ads a')
                ->where('a.type = ?', 'banner')
                ->orderBy('a.metadata', 'asc')
                ->execute();

        foreach($ads as $obj)
        {
            $data[$obj->position][] = $obj;
        }

        $this->template->main = View::factory('admin/ads_order', $data);
    }

    /**
     * Update order
     *
     * @access public
     */
    public function action_update_order()
    {
        $position = $_POST['position'];
        // Get order
        foreach($_POST[$position] as $order => $banner_id)
        {
            $banner = AdsTable::getInstance()->find($banner_id);

            if($banner !== NULL)
            {
                $banner->metadata = (string) $order;
                $banner->save();
            }
        }
    }

    /**
     *  Update ads's link
     */
    public function action_update_link()
    {
        if($this->request->is_ajax())
        {
            $this->auto_render = false;
            
            $id = Security::xss_clean($_POST['id']);
            $link = Security::xss_clean($_POST['link']);
            
            $ad = Doctrine_Query::create()
                                    ->from('Ads a')
                                    ->where('a.id = ?',$id)->fetchOne();
            if(!$ad)
                return false;
            
            $ad->url = $link;
            $ad->save();
        }    
    }
}
